package withouther.system.core.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import withouther.system.core.security.entity.UserInfo;
import withouther.system.plugins.system.entity.User;
import withouther.system.plugins.system.service.UserService;

import java.util.*;

@Slf4j
@Service
public class JwtUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        User user = userService.getOne(queryWrapper);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：" + username + " 不存在.");
//            throw new BadCredentialsException("登录用户：" + username + " 不存在");
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        Collection<? extends GrantedAuthority> authorities = getUserAuthorities(user.getId());
        authorities.forEach(System.out::println);
//        List<GrantedAuthority> authorities = new ArrayList<>();
//        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return new UserInfo(user.getId(), user.getUserName(), user.getPassword(), (List<GrantedAuthority>) authorities,true);
    }
    /**
     * 封装 根据用户Id获取权限
     *
     * @param userId
     * @return
     */
    private Collection<? extends GrantedAuthority> getUserAuthorities(Long userId) {
        // 获取用户拥有的角色
        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        // 权限集合
        Set<String> permissions = userService.findPermsByUserId(userId);
        // 角色集合
        Set<String> roleIds = userService.findRoleIdByUserId(userId);
        permissions.addAll(roleIds);
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]));
        return authorities;
    }
}
